package controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
	"server/component/errorx"
)

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

func ResultSuccess(c *gin.Context, data any) {
	resp := &Response{
		Code: 0,
		Msg:  "success",
		Data: data,
	}
	c.AbortWithStatusJSON(http.StatusOK, resp)
}

func ResultError(c *gin.Context, err error) {
	resp := &Response{Code: 400, Msg: err.Error()}

	var e *errorx.Error
	if errors.As(err, &e) {
		resp.Code = e.Code
		resp.Msg = e.Message
		c.AbortWithStatusJSON(http.StatusOK, resp)
	} else {
		resp.Code = 500
		resp.Msg = err.Error()
		c.AbortWithStatusJSON(http.StatusInternalServerError, resp)
	}
}
